import * as vscode from 'vscode';

export interface HighlightOptions {
    filePath: string;
    line: number;
    column: number;
    description: string;
}

export class HighlightManager {
    private activeHighlights = new Map<string, vscode.TextEditorDecorationType[]>();
    private activeCloseButtons = new Map<string, vscode.TextEditorDecorationType[]>();
    private diagnosticCollection: vscode.DiagnosticCollection;
    private extensionUri: vscode.Uri;

    constructor(extensionUri: vscode.Uri, diagnosticCollection: vscode.DiagnosticCollection) {
        this.extensionUri = extensionUri;
        this.diagnosticCollection = diagnosticCollection;
    }

    public highlightError(options: HighlightOptions): void {
        const { filePath, line, column, description } = options;
        
        // 清除该文件之前的所有装饰器
        this.clearHighlight(filePath);
        
        vscode.workspace.openTextDocument(filePath).then(doc => {
            vscode.window.showTextDocument(doc).then(editor => {
                const position = new vscode.Position(line - 1, column);
                const selection = new vscode.Selection(position, position);
                editor.selection = selection;
                editor.revealRange(
                    new vscode.Range(position, position),
                    vscode.TextEditorRevealType.InCenter
                );

                const highlight = this.createHighlightDecoration();
                const closeButton = this.createCloseButtonDecoration();
                
                // 存储装饰器数组
                this.activeHighlights.set(filePath, [highlight]);
                this.activeCloseButtons.set(filePath, [closeButton]);

                const range = new vscode.Range(position, position.translate(1, 0));
                editor.setDecorations(highlight, [range]);
                editor.setDecorations(closeButton, [range]);

                const diagnostic = new vscode.Diagnostic(
                    range,
                    description,
                    vscode.DiagnosticSeverity.Warning
                );
                this.diagnosticCollection.set(vscode.Uri.file(filePath), [diagnostic]);
            });
        }, err => {
            vscode.window.showErrorMessage(`打开文件 ${filePath} 失败: ${err}`);
        });
    }

    public clearHighlight(filePath: string): void {
        const highlights = this.activeHighlights.get(filePath) || [];
        const closeButtons = this.activeCloseButtons.get(filePath) || [];

        // 清理所有装饰器
        highlights.forEach(highlight => highlight.dispose());
        closeButtons.forEach(button => button.dispose());
        
        this.activeHighlights.delete(filePath);
        this.activeCloseButtons.delete(filePath);
        this.diagnosticCollection.delete(vscode.Uri.file(filePath));
    }

    public clearAllHighlights(): void {
        this.activeHighlights.forEach(highlights => highlights.forEach(h => h.dispose()));
        this.activeCloseButtons.forEach(buttons => buttons.forEach(b => b.dispose()));
        this.activeHighlights.clear();
        this.activeCloseButtons.clear();
        this.diagnosticCollection.clear();
    }

    public dispose(): void {
        this.clearAllHighlights();
    }

    private createHighlightDecoration(): vscode.TextEditorDecorationType {
        return vscode.window.createTextEditorDecorationType({
            isWholeLine: true,
            backgroundColor: 'rgba(255, 0, 0, 0.15)',
            border: '1px solid rgba(255, 0, 0, 0.3)',
            borderWidth: '0 0 0 3px',
            gutterIconPath: this.extensionUri.with({ path: this.extensionUri.path + '/warning.svg' }),
            gutterIconSize: 'contain',
            overviewRulerColor: 'rgba(255, 0, 0, 0.5)',
            overviewRulerLane: vscode.OverviewRulerLane.Right,
            after: {
                contentText: "执行发生错误",
                color: 'rgba(255, 0, 0, 0.7)',
                fontWeight: 'bold',
                margin: '0 0 0 10px'
            }
        });
    }

    private createCloseButtonDecoration(): vscode.TextEditorDecorationType {
        return vscode.window.createTextEditorDecorationType({
            gutterIconPath: vscode.Uri.parse(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(`
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
                    <path fill="currentColor" d="M7.293 8l-2.147-2.146a.5.5 0 1 1 .708-.708L8 7.293l2.146-2.147a.5.5 0 0 1 .708.708L8.707 8l2.147 2.146a.5.5 0 0 1-.708.708L8 8.707l-2.146 2.147a.5.5 0 0 1-.708-.708L7.293 8z"/>
                </svg>
            `)}`),
            gutterIconSize: 'contain',
            overviewRulerColor: 'rgba(255, 0, 0, 0.5)',
            overviewRulerLane: vscode.OverviewRulerLane.Right,
            light: {
                gutterIconPath: vscode.Uri.parse(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(`
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
                        <path fill="rgba(255, 0, 0, 0.7)" d="M7.293 8l-2.147-2.146a.5.5 0 1 1 .708-.708L8 7.293l2.146-2.147a.5.5 0 0 1 .708.708L8.707 8l2.147 2.146a.5.5 0 0 1-.708.708L8 8.707l-2.146 2.147a.5.5 0 0 1-.708-.708L7.293 8z"/>
                    </svg>
                `)}`)
            },
            dark: {
                gutterIconPath: vscode.Uri.parse(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(`
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
                        <path fill="rgba(255, 100, 100, 0.9)" d="M7.293 8l-2.147-2.146a.5.5 0 1 1 .708-.708L8 7.293l2.146-2.147a.5.5 0 0 1 .708.708L8.707 8l2.147 2.146a.5.5 0 0 1-.708.708L8 8.707l-2.146 2.147a.5.5 0 0 1-.708-.708L7.293 8z"/>
                    </svg>
                `)}`)
            }
        });
    }
}
